﻿using System.Linq.Expressions;
using SqlSugar;
using Digitalmes.Domain;

namespace Digitalmes.Sugar;

public static class SugarRepositoryExtensions
{
    /// <summary>
    /// 根据筛选条件，根据按 <see cref="IEntityBaseId.Id"/> 排序获取最新的一条数据。
    /// </summary>
    /// <param name="where">拉姆达条件</param>
    /// <returns></returns>
    public static async Task<T?> GetLastAsync<T>(this SugarRepository<T> repo, Expression<Func<T, bool>> where)
        where T : class, IEntityBaseId, new()
    {
        return await repo.Context.Queryable<T>()
            .Where(where)
            .OrderBy(m => new { m.Id }, OrderByType.Desc)
            .FirstAsync();
    }

    /// <summary>
    /// 逻辑删除。
    /// </summary>
    /// <param name="id">要删除的实体 Id</param>
    /// <returns></returns>
    public static async Task<bool> FakeDeleteByIdAsync<T>(this SugarRepository<T> repo, long id)
        where T : class, IEntityBaseId, new()
    {
        if (typeof(IDeletedFilter).IsAssignableFrom(typeof(T)))
        {
            return await repo.AsUpdateable().SetColumns(nameof(IDeletedFilter.IsDel), true)
                .Where(s => s.Id == id)
                .ExecuteCommandAsync() > 0;
        }

        return await repo.DeleteByIdAsync(id);
    }

    /// <summary>
    /// 逻辑删除。
    /// </summary>
    /// <param name="whereExpression">删除实体的筛选条件表达式</param>
    /// <returns></returns>
    public static async Task<bool> FakeDeleteAsync<T>(this SugarRepository<T> repo, Expression<Func<T, bool>> whereExpression)
        where T : class, IEntityBaseId, new()
    {
        if (typeof(IDeletedFilter).IsAssignableFrom(typeof(T)))
        {
            return await repo.AsUpdateable().SetColumns(nameof(IDeletedFilter.IsDel), true)
                .Where(whereExpression)
                .ExecuteCommandAsync() > 0;
        }

        return await repo.DeleteAsync(whereExpression);
    }
}
